import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClienteSocketSample{
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	JanelaLog janela;
	ClienteSocketSample(){
		janela = JanelaLog.getInstance(this);
		janela.setVisible(true);
	}
	void run()
	{
		try{
			//Cria um socket para se conectar com server 
			requestSocket = new Socket("localhost", 2004);
			janela.log("Connected to localhost in port 2004");

			//cria os input e output stream para troca de msg
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			
			out.writeObject("c");
			out.flush();

			//comunica com o servidor - protocolo simples
			do{
				try{
					message = (String)in.readObject();

					//mostra que o servidor esta UP
					janela.log("server>" + message);

					//Servidor responde
					message = (String)in.readObject();
					janela.log("server>" + message);

					message = "bye";

					//enia a mensagem de finalizacao
					sendMessage(message);
				}
				catch(ClassNotFoundException classNot){
					janela.log("Formato nao reconhecido");
				}
			}while(!message.equals("bye"));
		}
		catch(UnknownHostException unknownHost){
			janela.log("Servidor nao existe");
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//Fecha conexao
			try{
				in.close();
				out.close();
				requestSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}

	// Metodo para abstrair envio de mensagem
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			janela.log("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		ClienteSocketSample client = new ClienteSocketSample();
		client.run();
	}
}